package cn.jbt.api.admin.filter;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import java.io.IOException;

@Slf4j
public class LoginFilter implements Filter {

    /**
     * 忽略检查的url地址
     */
    private final String[] excludeUrls = new String[]{
            "/admin/system/login/token",
    };

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        // 过滤请求路径
        for (String uri : excludeUrls) {
            if (request.getRequestURI().equals(uri)) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        try {
            StpUtil.checkLogin();
        } catch (Exception e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}

